package com.itheima.mall.api.ums;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mall.mapper.ums.UmsResourceMapper;
import com.itheima.mall.mapper.ums.UmsRoleResourceRelationMapper;
import com.itheima.mall.pojo.ums.UmsResource;
import com.itheima.mall.pojo.ums.UmsRoleResourceRelation;
import com.itheima.mall.vo.R;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class UmsRoleResourceRelationServiceImpl implements UmsRoleResourceRelationServiceApi {

    @Autowired
    UmsRoleResourceRelationMapper umsRoleResourceRelationMapper;

    @Autowired
    UmsResourceMapper umsResourceMapper;

    @Override
    public R UmsRoleAllocResource(Long[] resourceIds, Long roleId) {

        int flag = 0;
        for (Long resourceId : resourceIds) {
            UmsRoleResourceRelation umsRoleResourceRelation = new UmsRoleResourceRelation();
            umsRoleResourceRelation.setResourceId(resourceId);
            umsRoleResourceRelation.setRoleId(roleId);
            int i = umsRoleResourceRelationMapper.insert(umsRoleResourceRelation);
            flag += i;
        }

        if (flag>0){
            return R.succeed("","创建成功");
        }

        return R.error("创建失败");
    }

    @Override
    public R UmsRoleListResource(Long id) {
        LambdaQueryWrapper<UmsRoleResourceRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ObjectUtil.isNotNull(id),UmsRoleResourceRelation::getRoleId,id);
        List<UmsRoleResourceRelation> umsRoleResourceRelations = umsRoleResourceRelationMapper.selectList(lqw);

        List<UmsResource> umsResourceList = new ArrayList<>();
        for (UmsRoleResourceRelation umsRoleResourceRelation : umsRoleResourceRelations) {
            UmsResource umsResource = umsResourceMapper.selectById(umsRoleResourceRelation.getResourceId());
            umsResourceList.add(umsResource);
        }
        return R.succeed(umsResourceList,"查找成功");    }
}
